<%@ page import="java.io.File"%>
<%@ page import="java.util.List"%>

<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>

<%
  List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
  if (items != null) {
      String uploadPath = null;
      for (FileItem item : items) {
          if (item.isFormField()) {
              String fieldName = item.getFieldName();
              if ("uploadPath".equals(fieldName)) {
                  uploadPath = item.getString();
                  break;
              }
          }
      }

      if (uploadPath != null) {
          for (FileItem item : items) {
              if (!item.isFormField()) {
                  String fileName = item.getName();
                  File uploadedFile = new File(uploadPath + File.separator + fileName);
                  item.write(uploadedFile);
                  System.out.println("Uploaded file to " + uploadedFile.getCanonicalPath());
                  break;
              }
          }
      }
  }

  response.sendRedirect("index.jsp");
%>
